import socket
import threading

client_conn = None  # 存储内网客户端的连接
lock = threading.Lock()

def start_control_server():
    """监听内网客户端的连接"""
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('0.0.0.0', 7000))  # 控制通道端口
    server.listen(1)
    print("Control server started on :7000")

    global client_conn
    while True:
        conn, addr = server.accept()
        print(f"Client connected from {addr}")
        with lock:
            client_conn = conn
        handle_client(conn)

def handle_client(conn):
    """保持与客户端的长连接"""
    try:
        while True:
            conn.recv(1024)  # 检测连接是否存活
    except:
        print("Client disconnected")
        with lock:
            global client_conn
            client_conn = None
        conn.close()

def start_proxy_server():
    """监听外部请求并转发"""
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('0.0.0.0', 9000))  # 代理端口
    server.listen(5)
    print("Proxy server started on :9000")

    while True:
        conn, addr = server.accept()
        print(f"External connection from {addr}")
        threading.Thread(target=handle_proxy, args=(conn,)).start()

def handle_proxy(conn):
    """将外部请求转发到内网客户端"""
    with lock:
        if not client_conn:
            print("No client available")
            conn.close()
            return
        target_conn = client_conn

    # 双向转发
    threading.Thread(target=forward, args=(conn, target_conn)).start()
    forward(target_conn, conn)

def forward(src, dst):
    """数据转发"""
    try:
        while True:
            data = src.recv(1024)
            if not data:
                break
            dst.send(data)
    except:
        pass
    finally:
        src.close()

if __name__ == "__main__":
    threading.Thread(target=start_control_server).start()
    start_proxy_server()